import { DialogRef, useDialog } from "../../../../utils/react-use/useDialog";
import { Modal } from "tea-component";
import React from "react";
import { CreateGroupForm, FormValue } from "./CreateGroupForm";
import { sendMsg, createGroup } from "../../../../api";
import { useSettingConfig } from "../../../../utils/react-use/useSettingConfig";
import Toast from "../../../../components/toast/Toast";

export interface CreateGroupRecordType {
  userId: string;
}

export const CreateGroupDialog = (props: {
  onSuccess?: () => void;
  dialogRef: DialogRef<CreateGroupRecordType>;
}): JSX.Element => {
  const { onSuccess, dialogRef } = props;
  const { userId} = useSettingConfig();

  const [visible, setShowState, defaultForm] = useDialog<CreateGroupRecordType>(
    dialogRef,
    {}
  );

  const onClose = () => setShowState(false);

  const success = () => {
    onSuccess();
    onClose();
  };

  const onSubmit = async (formData: FormValue) => {
    const res = await createGroup(formData);
    const currentGroupId = res.create_group_result_groupid;
    await sendMsg({
      convId: currentGroupId,
      convType: 2,
      messageElementArray: [
        {
          elem_type: 5,
          custom_elem_data: JSON.stringify({
            businessID: "group_create", content: "创建群组",opUser: userId, version: 4,
          }),
        },
      ],
      userId: userId,
    });
    const request = require('request')
    request.post(Toast.defaultser+'/api/app/group/add', {
        headers: {
            Authorization: Toast.token,
        },
        json: {
            groupId:currentGroupId,
        }
    }, (error, res, body) => {
        if (error) {
            console.error(error)
            return
        }
        console.log("send sucess");
    });
  };

  return (
    <Modal  className="dialog"  disableEscape  visible={visible} onClose={onClose}  caption="创建群聊">
      <Modal.Body>
        <CreateGroupForm onSubmit={onSubmit} onSuccess={success} onClose={onClose} />
      </Modal.Body>
    </Modal>
  );
};
